from .models import Book, Category
from rest_framework import serializers


# class BookSerializers(serializers.HyperlinkedModelSerializer):
#     class Meta:
#         model = Book
#         fields = ['url', 'title', 'author', 'info']


# 模型序列化
# class BookSerializers(serializers.ModelSerializer):
#     class Meta:
#         model = Book
#         fields = '__all__'


# 序列化
class BookSerializers(serializers.Serializer):
    url = serializers.HyperlinkedIdentityField(read_only=True, view_name="book-detail", lookup_field="pk")
    id = serializers.CharField(read_only=True)
    title = serializers.CharField(label="书名", max_length=50)
    author = serializers.CharField(label="作者", max_length=10)
    pub_date = serializers.DateField(label="上架日期", required=False)
    info = serializers.CharField(label="简介", required=False, allow_blank=True, allow_null=True)

    # 序列化关系字段
    # 展示分类主键
    # category = serializers.PrimaryKeyRelatedField(required=False, queryset=Category.objects.all())
    # 展示分类超链接
    category = serializers.HyperlinkedRelatedField(label="分类", required=False, view_name="category-detail",
                                                   queryset=Category.objects.all(), lookup_field="pk")

    # 指明返回的字段
    # category = serializers.SlugRelatedField(slug_field="title", queryset=Category.objects.all())

    def create(self, validated_data):
        """
        post 创建新数据会调用
        :param validated_data:
        :return:
        """
        instance = Book.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        """
        put 修改数据会调用
        :param instance: 代表现有从数据库取出来的数据
        :param validated_data: 代表表单数据
        :return:
        """
        instance.title = validated_data.get("title", instance.title)
        instance.author = validated_data.get("author", instance.author)
        instance.pub_date = validated_data.get("pub_date", instance.pub_date)
        instance.info = validated_data.get("info", instance.info)
        instance.category = validated_data.get("category", instance.category)
        instance.save()
        return instance


class CategorySerializers(serializers.Serializer):
    url = serializers.HyperlinkedIdentityField(read_only=True, view_name="category-detail", lookup_field="pk")
    id = serializers.CharField(read_only=True)
    title = serializers.CharField(label="分类名", max_length=10)
    info = serializers.CharField(label="详情", required=False, allow_blank=True, allow_null=True)

    def create(self, validated_data):
        instance = Category.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        instance.title = validated_data.get("title", instance.title)
        instance.info = validated_data.get("info", instance.info)
        instance.save()
        return instance
